import time
from datetime import datetime, timedelta

from flask import g
from flask import request
from flask import session

from info import constants, db
from info.image_storage import storage
from info.models import News,Comment, User, Category
from info.utils.common import login_user_data
from info.utils.response_code import RET
from . import admin_blue
from flask import render_template, current_app, jsonify

@admin_blue.route('/index')
@login_user_data
def admin_index():
    user=g.user
    return render_template('admin/index.html',user=user.to_dict()if user else None)


@admin_blue.route('/login',methods=['GET','POST'])
@login_user_data
def login():
    user = g.user
    #get方法
    if request.method=='GET':
        is_admin=session.get('is_admin',False)
        if user and is_admin:
            return render_template('admin/index.html',user=user.to_dict()if user else None)

        return render_template('admin/login.html')


    #post方法话
    #从提交的表单数据中拿到数据
    password=request.form.get('password')
    username=request.form.get('username')
    if not all([password,username]):
        return render_template('admin/login.html',errmsg='参数不全')
    #校验参数
    try:
        user=User.query.filter(User.mobile==username,User.is_admin==True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html',errmsg='数据库查询错误')
    #返回模板
    if not user or not user.check_password(password):
        return render_template('admin/login.html', errmsg='用户名或密码错误')

    user_id=user.id
    nick_name=user.nick_name

    session['is_admin']=True
    session['nick_name']=nick_name
    session['user_id']=user_id

    return render_template('admin/index.html',user=user.to_dict()if user else None)


@admin_blue.route('/logout',methods=['POST','GET'])
@login_user_data
def logout():
    session.pop('user_id')
    session.pop('is_admin')
    session.pop('nick_name')
    return render_template('admin/login.html')


@admin_blue.route('/user_count')
@login_user_data
def user_count():

# 用户总数
# data.total_count
    total_count=0
    try:
        total_count=User.query.filter(User.is_admin==False).count()
    except Exception as e:
        current_app.logger.error(e)
# 用户月新增数 mon_count
    mon_count=0
    now = time.localtime()
    try:
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        mon_begin = datetime.strptime(mon_begin, '%Y-%m-%d')
        mon_count=User.query.filter(User.is_admin==False,User.create_time>=mon_begin).count()
    except Exception as e:
        current_app.logger.error(e)

    # 用户日增数 data.day_count
    day_count=0
    try:
        day_begin='%d-%02d-%02d'%(now.tm_year,now.tm_mon,now.tm_mday)
        day_count=User.query.filter(User.is_admin==False,User.create_time>=day_begin).count()
    except Exception as e:
        current_app.logger.error(e)
# data.active_date
    active_date=[]
    active_count=[]
    now_date_str=datetime.now().strftime('%Y-%m-%d')
    now_date= datetime.strptime(now_date_str,'%Y-%m-%d')
    try:
        for i in range(0,31):
            #每一天的开始时间开始算
            begin_date=now_date-timedelta(days=i)
            end_date=now_date-timedelta(days=i-1)
            day_active_count=User.query.filter(User.is_admin==False,User.last_login>=begin_date,User.last_login<end_date).count()
            begin_date=begin_date.strftime('%Y-%m-%d')
            active_date.append(begin_date)
            active_count.append(day_active_count)
    except Exception as e:
        current_app.logger.error(e)

    active_count.reverse()
    active_date.reverse()

    data={
        'total_count':total_count,
        'mon_count':mon_count,
        'day_count':day_count,
        'active_date':active_date,
        'active_count':active_count
    }
    return render_template('admin/user_count.html',data=data)


@admin_blue.route('/user_list')
def user_list():
    #获取页码参数,拿不到则设置默认值为1
    page=request.args.get('p',1)
    #校验参数,设置默认值为1
    try:
        page=int(page)
    except Exception as e:
        current_app.logger.error(e)
        page=1
    #根据页码以及每页的用户数拿到分页模型
    try:
        paginate=User.query.filter(User.is_admin==False).paginate(page,constants.ADMIN_USERS_PERMAX,False)
        current_page=paginate.page
        total_page=paginate.pages
        users=paginate.items
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        current_page=1
        total_page=1
        users=[]
    user_list=[]
    for user in users:
        user_list.append(user.to_admin_dict())

    data={
        'current_page':current_page,
        'total_page':total_page,
        'users':user_list
    }
    return render_template('admin/user_list.html',data=data)
    #返回total_page current_page users


@admin_blue.route('/news_review')
def news_review():
    #先获取页数参数,设置默认值1
    page=request.args.get('p',1)
    #获取关键字参数，默认值""
    keywords=request.args.get('keywords',"")
    #校参数
    try:
        page=int(page)
    except Exception as e:
        current_app.logger.error(e)
        page=1
    #如果有关键字 则在新闻过滤条件中加上这个关键字
    filters=[News.status!=0]
    if keywords:
        filters.append(News.title.contains(keywords))
    #查询新闻模型
    try:
        paginate=News.query.filter(*filters)\
            .order_by(News.create_time.desc())\
            .paginate(page,constants.ADMIN_NEWS_PERMAX,False)
        news_model=paginate.items
        current_page=paginate.page
        total_page=paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        news_model=[]
        current_page=1
        total_page=1
        
    news_list=[]
    #返回 news_list，current_page,total_page
    for news in news_model:
        news_list.append(news.to_review_dict())
    
    data={
        'current_page':current_page,
        'total_page':total_page,
        'news_list':news_list
    }
    
    return render_template('admin/news_review.html',data=data)


@admin_blue.route('/news_review_detail',methods=['GET','POST'])
def news_review_detail():
    if request.method=='GET':
        #先拿args news_id以及判断参数的正确性以及完整性
        news_id=request.args.get('news_id')
        if not news_id:
            return render_template('admin/news_review_detail.html',errmsg='参数不正确')
        
        news=None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        
        if not news:
            return render_template('admin/news_review.html',errmsg='参数不正确')

        data={
            'news':news.to_dict()
        }
        return render_template('admin/news_review_detail.html',data=data)


    news_id=request.json.get('news_id')
    action=request.json.get('action')
    # reason=request.json.get('reason')

    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    if action not in('accept','reject'):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不正确')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    if not news:
        return jsonify(errno=RET.PARAMERR,errmsg='未查询到消息')

    if action=='accept':
        news.status=0
    else:
        reason=request.json.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR,errmsg='参数不全')
        news.status=-1
        news.reason=reason
    
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据保存失败')
        
    return jsonify(errno=RET.OK,errmsg='审核成功')



@admin_blue.route('/news_edit')
def news_edit():
    """返回新闻列表"""

    page = request.args.get("p", 1)
    keywords = request.args.get("keywords", "")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1

    try:
        filters = []
        # 如果有关键词
        if keywords:
            # 添加关键词的检索选项
            filters.append(News.title.contains(keywords))

        # 查询
        paginate = News.query.filter(*filters) \
            .order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PERMAX, False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    context = {"total_page": total_page, "current_page": current_page, "news_list": news_dict_list}

    return render_template('admin/news_edit.html', data=context)


@admin_blue.route('/news_edit_detail',methods=['GET','POST'])
def news_edit_detail():
    #get方式下,获取News_id参数
    if request.method=='GET':
        news_id=request.args.get('news_id')

        if not news_id:
            return render_template('admin/news_edit_detail.html',errmsg='新闻参数不全')
        #根据新闻id查询新闻模型
        try:
            news=News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            news=None

        if news==None:
            return render_template('admin/news_edit_detail.html',errmsg='未查询到该新闻')

        #拿到分类数据
        try:
            category_model=Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html', errmsg='数据库错误')

        categories=[]

        for category in category_model:
            # 在类别中增加一个字段'is_selected'来标记该新闻的类别号
            category_dic=category.to_dict()
            category_dic['is_selected']=False
            if category.id==news.category_id:
                category_dic['is_selected']=True
            categories.append(category_dic)

        data={
            'news':news.to_dict(),
            'categories':categories
        }
        return render_template('admin/news_edit_detail.html',data=data)
    #在新闻类别中增加一个字段'is_selected'来标记被选中的新闻类别号
    #返回字典

    #post请求下
    #拿到digst,content,title,index_image,category_id,
    news_id=request.form.get('news_id')
    digest=request.form.get('digest')
    content=request.form.get('content')
    title=request.form.get('title')
    index_image=request.files.get('index_image')
    category_id=request.form.get('category_id')
    #验证参数的完整性
    if not all([digest,content,title,category_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')
        # 根据news_id拿出新闻模型,更改新闻数据
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='未查询到该新闻')
    #如果有图片 上传图片数据 并保存图片地址
    if index_image:
        try:
            index_image=index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR,errmsg='参数不正确')

        try:
            key=storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR,errmsg='数据库错误')
        news.index_image_url = constants.QINIU_DOMIN_PREFIX+key
    #上传至数据库
    news.content=content
    news.category_id=category_id
    news.digest=digest
    news.title=title
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库错误')


    return jsonify(errno=RET.OK,errmsg='更新成功')



@admin_blue.route('/news_type',methods=['POST','GET'])
def news_type():
    #如果请求方式是GET，返回模板 以及data:categories数据
    if request.method=='GET':
        try:
            category_models=Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库错误')

        categories=[]

        for category in category_models:
            categories.append(category.to_dict())

        data={'categories':categories}

        return render_template('admin/news_type.html',data=data)
    #POST请求的话,拿到参数id和name
    id=request.json.get("id")
    name=request.json.get('name')
    #校验是否有name 因为无论是编辑还是添加分类 都需要传来name
    if not name:
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')
    #如果有ID 根据ID查找分类模型
    if id:
        try:
            category=Category.query.get(id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库错误')

        if not category:
            return jsonify(errno=RET.PARAMERR,errmsg='未查询到分类数据')
    #修改模型数据
        category.name=name
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库错误')
        return jsonify(errno=RET.OK,errmsg='修改成功')
    #如果没有,新建一个分类模型
    new_category=Category()
    new_category.name=name
    try:
        db.session.add(new_category)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    return jsonify(errno=RET.OK,errmsg='添加成功')
